import WxValidate from '../../utils/WxValidate';
const {
  request
} = require("../../utils/index.js")
const {
  uploadFile
} = require("../../utils/toasync.js")
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    graduimg: '', //毕业照或录取通知书图片
    graduID:[],  //毕业证或录取通知书图片ID
    graduList: [], //毕业照或录取通知书临时图片路径
    gradunum: [], //毕业照或录取通知书已选个数
    Documentsimg: '', //相关证件图片
    uploaderID:[],  //相关证件图片ID
    uploaderList: [], //证件相关已选图片临时路径
    uploaderNum: 0, //证件相关已选图片个数
    gradushow: true, //毕业照或录取通知书是否可以继续选择图片
    showUpload: true, //证件相关是否可以继续选择图片
    realname:null,  //用户认证信息
    banjiValue:"",
    cqValue:"",
    raldisplay:false,  //认证信息是否只读
    raldisplay2:"aotu",  //认证信息是否只读
    items: [{
        value: '春季',
        name: '春季',
        checked: 'true'
      },
      {
        value: '秋季',
        name: '秋季'
      },
    ],
  },

	//单选框数据更改
  radioChange(e){
    this.setData({
      cqValue:e.detail.value
    })
  },
  banji(e){
    this.setData({
      banjiValue:e.detail.value+"班"
    })
  },
  // 获得实名认证的信息
  async getrealname(potions) {
    let par = {
      url:"hw/portal/user/show/user_cert?token="+wx.getStorageSync('token'),
      method: "GET",
      header:{
       'content-type': 'application/json', // 默认值
      },
    }
    let datainfo = await request(par);  //用户认证信息
    if(datainfo.status==100){
      if(JSON.stringify(datainfo.data)=="{}"||datainfo.data==undefined){
        return;//未实名
      }
      this.setData({
        realname:datainfo.data,
        'realname.studentNo':datainfo.data.studentNo
      })
      if(datainfo.data.diplomaImg!=undefined){
        this.setData({
          graduList:[datainfo.data.diplomaImg],
        })
      }
      if(this.data.realname.auditStatus!=undefined){
        if(this.data.realname.auditStatus.code=='wait'||this.data.realname.auditStatus.code=='success'){
          this.setData({
            raldisplay:true,   //实名信息为只读
            raldisplay2:"none"   //实名信息为只读
          })
        }
      }
    }
  },

  //毕业证或录取通知书图片上传
  gradupload: function (event) {
    var that = this;
    wx.chooseImage({
      count: 1 - that.data.gradunum,
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        var tempFilePaths = res.tempFilePaths;
        wx.uploadFile({
          url: 'https://tms.sds.com.cn:8300/hw/upload/files',
          filePath: tempFilePaths[0],
          name: 'file',
          header: {
            'Content-Type': 'multipart/form-data',
          },
          formData: {
            method: 'POST',
            token: wx.getStorageSync('token'),
            sortVal: 1,
            updFileModule: 'user_diploma',
            updFileType: 'pic',
          },
          success(res2) {
            var res = JSON.parse(res2.data)
            if (res.status == 100) {
              var graduList = that.data.graduList.concat(res.data.updUrl);
              if (graduList.length == 1) {
                that.setData({
                  gradushow: false
                })
              }
              that.data.graduID.push(res.data.updId)
              that.setData({
                graduList: graduList,
                gradunum: graduList.length
              })
            }
          },
          fail(err) {
            console.log(err)
          }
        })
      }
    })
  },

  //毕业证或录取通知书图片展示
  gradushow: function (e) {
    var that = this;
    wx.previewImage({
      urls: that.data.graduList,
      current: that.data.graduList[e.currentTarget.dataset.index]
    })
  },

  //毕业证或录取通知书图片删除
  gradudele: function (e) {
    var newimg = []; //删除后新数据
    var graduList = this.data.graduList; //删除前数据
    for (let i = 0; i < graduList.length; i++) {
      if (i == e.currentTarget.dataset.index) {
        continue;
      } else {
        newimg.push(graduList[i])
      }
    }
    this.setData({
      graduList:[],
      gradushow: true
    })
  },

  //相关证件资料图片上传
  uploadimg: function (e) {
    var that = this;
    wx.chooseImage({
      count: 6 - that.data.uploaderNum,
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        var tempFilePaths2 = res.tempFilePaths;
        wx.uploadFile({
          url: 'https://tms.sds.com.cn:8300/hw/upload/files',
          filePath: tempFilePaths2[0],
          name: 'file',
          header: {
            'Content-Type': 'multipart/form-data',
          },
          formData: {
            method: 'POST',
            token: wx.getStorageSync('token'),
            sortVal: 1,
            updFileModule: 'user_cert',
            updFileType: 'pic',
          },
          success(res2) {
            var res = JSON.parse(res2.data)
            if (res.status == 100) {
              var uploaderList = that.data.uploaderList.concat(tempFilePaths2[0]);
              if (uploaderList.length == 3) {
                that.setData({
                  uploaderList:uploadFile,
                  showUpload: false
                })
              }
              that.data.uploaderID.push(res.data.updId)
              that.setData({
                uploaderList: uploaderList,
                uploaderNum: uploaderList.length
              })
            }
          },
          fail(err) {
            console.log(err)
          }
        })
      }
    })
  },
  //上传相关证件资料展示
  showimg: function (e) {
    var that = this;
    wx.previewImage({
      urls: that.data.uploaderList,
      current: that.data.uploaderList[e.currentTarget.dataset.index]
    })
  },
  
  //相关证件图片删除
  deleimg: function (e) {
    console.log(this.data.uploaderNum)
    var newimg = []; //删除后新数据
    var uploaderList = this.data.uploaderList; //删除前数据
    for (let i = 0; i < uploaderList.length; i++) {
      if (i == e.currentTarget.dataset.index) {
        continue;
      } else {
        newimg.push(uploaderList[i])
      }
    }
    this.setData({
      uploaderNum: this.data.uploaderNum - 1,
      uploaderList: newimg,
      showUpload: true
    })
  },

  // 非空验证
  initValidate() {
    const rules = {
      username: {
        required: true,
      },
      idCard: {
        required: true,
        idcard: true
      },
      tel:{
        required: true,
        tel: true
      },
      idCard3: {
        required: true,
      },
      idCard2: {
        required: false,
      },
      banji:{
        required: true,
      },
    }
    // 验证字段的提示信息，若不传则调用默认的信息
    const messages = {
      username: {
        required: '请输入真实姓名',
      },
      idCard: {
        required: '请输入身份证号',
        idCard: '请输入正确的身份证号'
      },
      tel:{
        required: '请输入手机号',
        tel: '请输入正确的手机号'
      },
      // idCard2: {
      //   required: '请输入毕业证号或学生证号'
      // },
      idCard3: {
        required: '请输入毕业或正在就读学院'
      },
      banji:{
        required: '请输入年级',
      },
    };
    // 创建实例对象
    this.WxValidate = new WxValidate(rules, messages)
  },
  async submitForm(e) {
    /*(表单提交校验)*/
    const params = e.detail.value
    if (!this.WxValidate.checkForm(params)) {
      const error = this.WxValidate.errorList[0]
      this.showModal(error)
      return false
    }
    if (this.data.graduList == null) {
      wx.showToast({
        title: '请上传毕业证或录取通知书图片',
      })
      return;
    }
    if(this.data.banjiValue==""){
      wx.showToast({
        title: '请输入班级',
        icon:"none"
      })
      return;
    }
    // 验证通过以后->
    console.log("真实姓名："+params.username)
    console.log("身份证："+params.idCard)
    console.log("手机号："+params.tel)
    console.log("毕业证或学生证号："+params.idCard2)
    console.log("学院简称："+params.idCard3)
    console.log("年级班级："+params.banji+"级"+this.data.banjiValue)
    console.log("学生证图片："+this.data.graduList.toString())
    console.log("相关证件照片："+this.data.uploaderID)
    if (this.data.graduList.length >= 1) {
      let parm = {
        url: 'hw/portal/user/upd_cert_info?token='+wx.getStorageSync('token'),
        data: {
          name: params.username,  //真实姓名
          idCard: params.idCard,  //身份证号
          userPhone:params.tel,  //手机号
          diplomaNo	: params.idCard2,  //毕业证或学生证号
          college: params.idCard3,  //学院简称
          classInfo:params.banji+"级"+this.data.cqValue+this.data.banjiValue,  //年级班级
          diplomaImg: this.data.graduList.toString(),   //学生证图片
          files:this.data.uploaderID,   //相关证件图片
        },
        method: 'POST',
        header: {
          'content-type': 'application/json', // 默认值
        },
      }
      let data = await request(parm);
      if(data.status==100){
        wx.showModal({    
          title: '提交成功！请等待管理员审核！',
          confirmText: "确认",
          showCancel: false,
          success:function(res){
            if(res.confirm){
              wx.navigateBack({
                delta: 1,
              })
            }
          }
        })
      }
    } else {
      console.log(this.data.graduList.length)
      wx.showToast({
        title: '请上传毕业证或录取通知书照片',
        icon: "none"
      })
    }
  },

  showModal(error) {
    wx.showModal({
      content: error.msg,
      showCancel: false,
    })
  },

  qux: function (potions) {
    wx.switchTab({
      url: '/pages/logs/logs',
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.initValidate();
    this.getrealname();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})